<template>
  <div class="app-container">
    <el-form
      :inline="true"
    >
      <el-form-item
        :label="$t('area.Layer')"
        prop="postName"
      >
        <treeselect
          v-model="mapId"
          size="small"
          :placeholder="$t('operating.pleaseChosen')"
          :show-count="true"
          :max-height="600"
          :options="mapTreeData"
          :default-expand-level="1"
          @input="nodeClick"
        />
      </el-form-item>
      <el-form-item
        :label="$t('history.date')"
        prop="postName"
      >
        <el-date-picker
          v-model="timeValue1"
          size="small"
          type="datetime"
          :placeholder="$t('operating.StartTime')"

          @change="change1"
        />
        -
        <el-date-picker
          v-model="timeValue2"
          type="datetime"
          size="small"
          :placeholder="$t('operating.EndTime')"

          @change="change2"
        />

      </el-form-item>
      <el-form-item
        :label="$t('area.queryArea')"
        prop="postName"
      >
        <el-select
          v-model="searchValue"
          size="small"
          :placeholder="$t('Notice.fenceAreaNotSelected')"
          style="width: 150px;"
          @change="handleFenceChange"
        >
          <el-option
            v-for="item in fenceData"
            :key="item.idx"
            :label="item.fenceName"
            :value="item.idx"
          />
        </el-select>

      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="query"
        >{{ $t("operating.search") }}</el-button>
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
            $t("operating.reset")
          }}</el-button> -->
      </el-form-item>
    </el-form>
    <!-- <el-header>

        <div class="handle-box">
          <span>{{$t('area.Layer')}}:</span>
          <treeselect v-model="mapId"
                      :placeholder="$t('operating.pleaseChosen')"
                      :show-count="true"
                      :maxHeight="600"
                      :options="mapTreeData"
                      :default-expand-level="1"
                      @input="nodeClick">
          </treeselect>
          <span>{{$t('area.queryArea')}}</span>
          <el-select v-model="searchValue"
                     :placeholder="$t('Notice.fenceAreaNotSelected')"
                     @change="handleFenceChange"
                     style="width: 150px;">
            <el-option v-for="item in fenceData"
                       :key="item.idx"
                       :label="item.fenceName"
                       :value="item.idx"></el-option>
          </el-select>
          <span>{{$t('history.date')}}:</span>
          <el-date-picker v-model="timeValue1"
                          type="datetime"
                          @change="change1"
                          :placeholder="$t('operating.StartTime')"
                          style="width:200px;">
          </el-date-picker>
          <el-date-picker v-model="timeValue2"
                          type="datetime"
                          @change="change2"
                          :placeholder="$t('operating.EndTime')"
                          style="width:200px;">
          </el-date-picker>
          <span>
            <el-button icon="el-icon-search"
                       @click="query"
                       style="background-color:#f1a11e; color: #fff;">{{ $t('operating.search')}}</el-button>
          </span>
        </div>
      </el-header> -->
    <div class="context">
      <div id="map" />
    </div>

    <!-- 表格形式显示 -->
    <el-table
      v-show="tableshow"
      ref="table"
      class="infotable"
      :data="trackDatas"
      max-height="400"
      :cell-style="setCellBackgroundColor"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="40"
      />
      <el-table-column
        prop="name"
        :label="$t('areaTrackPlayback.name')"
        width="80"
      />
      <el-table-column
        prop="departmentName"
        sortable
        :label="$t('areaTrackPlayback.department')"
        width="80"
      />
      <el-table-column
        prop="resourceId"
        :label="$t('areaTrackPlayback.tagId')"
        width="80"
      />
      <el-table-column
        prop="type"
        sortable
        :label="$t('areaTrackPlayback.type')"
        width="80"
      />
      <el-table-column
        prop="stylecolor"
        :label="$t('areaTrackPlayback.lineColor')"
        width="80"
      />
      <el-table-column
        prop="datalength"
        sortable
        :label="$t('areaTrackPlayback.theAmountOfData')"
        width="90"
      />
    </el-table>

    <!-- 左下角坐标显示和缩放比例 -->
    <div class="positiondiv">
      <span />
    </div>
    <div class="scalediv">
      <span />
    </div>

  </div>
</template>

<script>
import i18n from '@/utils/lang/index'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  sendThis,
  Load_Map,
  _iMap,
  _TransPixel,
  TagStyle,
  _Style,
  updateOverlayPosition,
  FenceStyle,
  _TransMetric,
  _TransMetricFence,
  _dPR,
  addSingleFence
} from '@/utils/historyMap.js'
import {
  webSockUrl,
  webSockStatisticsUrl,
  cameraServerUrl,
  baseUrl,
  initPicPath,
  webSockMonitorUrl,
  rateHeartShow
} from '@/utils/global'
import { Vector as VectorSource } from 'ol/source.js'
import { Vector as VectorLayer } from 'ol/layer.js'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import { LineString, MultiLineString } from 'ol/geom.js'
import { Style, Stroke } from 'ol/style.js'
import {
  getMapTree,
  getMap
} from '@/api/location'

import {
  getLayerFenceList,
  getFenceHistoryDisplayData
} from '@/api/system/historyDisplayInfo.js'

export default {
  components: { Treeselect },
  data() {
    return {
      mapId: '',
      oldMapId: null,
      mapTreeData: [],
      radio: '1',
      timeValue1: new Date(new Date().getTime() - 1000 * 60 * 30),
      timeValue2: new Date(),
      lineSource: null,
      lineLayer: null,
      rloading: [],
      fenceData: [],
      searchValue: null,
      tableshow: false,
      trackDatas: [],
      multipleSelection: [], // 表格中勾选的数据
      lineStyle: {
        'linestring': new Style({
          stroke: new Stroke({
            color: 'yellow',
            width: 1
          }),
          zIndex: 999
        })
      }
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    initData() {
      // 加载地图树
      getMapTree().then((res) => {
        const RES = this.responseUse(res)
        if (typeof RES !== 'undefined') {
          this.mapTreeData = RES
          sendThis(this)
          this.mapId = RES[0].id
          this.filterMapID(this.mapId)
        }
      })
    },
    nodeClick() {
      if (this.oldMapId == this.mapId) {
        this.$message({
          message: i18n.t('realtime.areaQequired'),
          type: 'warning'
        })
      } else if (this.mapId !== undefined) {
        this.oldMapId = this.mapId
        this.tableshow = false
        getMap(this.mapId).then(res => {
          const RES = this.responseUse(res)
          if (RES != undefined) {
            $('#map').empty()
            Load_Map(baseUrl + '/file' + RES.mapPath, RES.mapActualX,
              RES.mapActualY,
              RES.mapPixelX,
              RES.mapPixelY,
              RES.mapPixelX / RES.mapActualX, [RES.mapOriginX, RES.mapOriginY], false)
            this.loadLayer()
          }
        })
        this.filterMapID(this.mapId)
      }
    },
    change1() {
      if (this.timeValue1 > this.timeValue2) {
        var tt = this.timeValue1.getTime()
        var ntt = tt + 1000 * 60 * 120
        this.timeValue2 = new Date(ntt)
      }
    },
    change2() {
      if (this.timeValue2 < this.timeValue1) {
        var tt = this.timeValue2.getTime()
        var ntt = tt - 1000 * 60 * 120
        this.timeValue1 = new Date(ntt)
      }
    },
    query() {
      if (this.searchValue == null) {
        this.$message({
          message: i18n.t('Notice.fenceAreaNotSelected'),
          type: 'warning'
        })
        return
      }
      this.trackDatas = []
      this.tableshow = true
      this.lineSource.clear(true)
      // this.rloading = this.$loading({
      //   lock: true,
      //   text: i18n.t('areaTrackPlayback.loading'),
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0,0,0,0.7)'
      // })
      var param = {
        'mapId': parseInt(this.mapId),
        'fenceId': this.searchValue,
        'startTime': this.v_FormatDateTime(new Date(this.timeValue1).getTime()),
        'endTime': this.v_FormatDateTime(new Date(this.timeValue2).getTime())
      }
      getFenceHistoryDisplayData(param).then(res => {
        // this.rloading.close()
        const RES = this.responseUse(res)
        if (undefined != RES && RES.length > 0) {
          console.log(RES.length)
          for (var i = 0; i < RES.length; i++) {
            for (var k = 0; k < RES[i].data[0].length; k++) {
              RES[i].data[0][k] = _TransPixel(RES[i].data[0][k])
            }
            RES[i].stylecolor = this.getColor()
            switch (RES[i].type) {
              case 'staff': RES[i].type = this.$t('realtime.staff'); break
              case 'car': RES[i].type = this.$t('realtime.car'); break
              case 'visitor': RES[i].type = this.$t('realtime.celler'); break
              case 'material': RES[i].type = this.$t('realtime.material'); break
              case 'machine': RES[i].type = this.$t('realtime.machine'); break
              case 'boat': RES[i].type = this.$t('realtime.boat'); break
              default: RES[i].type = this.$t('realtime.unknow'); break
            }
            var lineFeature = new Feature(new LineString(RES[i].data[0]))
            lineFeature.setId(RES[i].resourceId)
            lineFeature.setStyle(new Style({
              stroke: new Stroke({
                color: RES[i].stylecolor,
                width: 2
              }),
              zIndex: 999
            }))
            this.lineSource.addFeature(lineFeature)
            this.trackDatas.push(RES[i])
            this.$refs.table.toggleRowSelection(this.trackDatas[i], true)
          }
        }
      })
    },
    // 加载地位图层和线图层,
    loadLayer() {
      this.lineSource = new VectorSource({
        wrapX: false
      })
      this.lineLayer = new VectorLayer({
        source: this.lineSource,
        style: new Style({
          stroke: new Stroke({
            color: 'green',
            width: 3
          })
        })
      })
      _iMap.addLayer(this.lineLayer)
    },
    handleFenceChange() {
      const url = baseUrl + '/fenceInfo/findByIdGeoJson?idx=' + this.searchValue
      addSingleFence(this.searchValue)
    },
    filterMapID(val) {
      getLayerFenceList(val).then(res => {
        const RES = this.responseUse(res)
        this.fenceData = RES
        this.searchValue = null
      })
    },
    handleSelectionChange(val) {
      this.lineSource.clear(true)
      for (var i = 0; i < val.length; i++) {
        var lineFeature = new Feature(new LineString(val[i].data[0]))
        lineFeature.setId(val[i].resourceId)
        lineFeature.setStyle(new Style({
          stroke: new Stroke({
            color: val[i].stylecolor,
            width: 2
          }),
          zIndex: 999
        }))
        this.lineSource.addFeature(lineFeature)
      }
    },
    setCellBackgroundColor(row) {
      const style = { backgroundColor: '#ffffff' }
      if (row.columnIndex === 5) {
        style.backgroundColor = row.row.stylecolor
      }
      return style
    },
    // 生成随机颜色
    getColor() {
      var str = '#'
      var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
      for (var i = 0; i < 6; i++) {
        var num = parseInt(Math.random() * 16)// 随机产生0-15之间的一个数
        str += arr[num]// 产生的每个随机数都是一个索引，根据索引找到数组中对应的值，拼接到一起
      }
      return str
    }
  }
}
</script>

<style scoped>

.handle-box {
  min-width: 1125px;
}

.handle-box * {
  float: left;
}

.handle-box span {
  line-height: 28px;
  margin-left: 30px;
}

.context {
  padding: 0;
  width: 100%;
  height: calc(100% - 60px);
}
.context div {
  float: left;
}
#map {
  width: 100%;
  height: 100%;
}

>>> .vue-treeselect__control {
  width: 180px;
}

.infotable {
  position: absolute;
  width: 530px;
  top: 60px;
  left: 50px;
}

 /deep/ .el-button--mini.is-circle {
  width: 36px;
  height: 36px;
}

</style>
